package cn.dengqiang.pet.service.impl;

import cn.dengqiang.basic.service.impl.BaseServiceImpl;
import cn.dengqiang.pet.domain.Pet;
import cn.dengqiang.pet.domain.PetDetail;
import cn.dengqiang.pet.mapper.PetDetailMapper;
import cn.dengqiang.pet.mapper.PetMapper;
import cn.dengqiang.pet.service.IPetService;
import cn.dengqiang.user.domain.User;
import cn.dengqiang.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;
    @Override
    public void del(Long id) {
        petMapper.remove(id);
        petDetailMapper.removeByPetId(id);
    }

    @Override
    public void add(Pet pet) {
        petMapper.save(pet);
        PetDetail detail = pet.getDetail();
        if (detail!=null){
            detail.setPet_id(pet.getId());
            petDetailMapper.save(detail);
        }
    }

    @Override
    public void update(Pet pet) {
        petMapper.update(pet);
        //是否有详情
        PetDetail detail = pet.getDetail();
        if (detail!=null){
            if (detail.getId()!=null){
                //有详情
                petDetailMapper.update(detail);
            }else{
                petDetailMapper.save(detail);
            }
        }
    }



    @Override
    public PetDetail getDetailByPetId(Long productId) {
        return null;
    }

    @Override
    public void onOrOffsale(List<Long> ids, int flag) {
        if (flag==1){
            Map<String,Object> params= new HashMap<>();
            params.put("onsaleTime",new Date());
            params.put("ids",ids);
            petMapper.onsale(params);
        }else {
            Map<String,Object> params= new HashMap<>();
            params.put("offsaleTime",new Date());
            params.put("ids",ids);
            petMapper.offsale(params);
        }
    }

    @Autowired
    private UserMapper userMapper;
    @Override
    public void adopt(Long id, Long loginInfoId) {
        Pet pet = petMapper.loadById(id);
        // 一 修改信息
        //1 宠物下架
        pet.setState(0);
        pet.setOffsaletime(new Date());
        //2 绑定用户
        User user = userMapper.loadByLoginfoId(loginInfoId);
        pet.setUser_id(user.getId());
        pet.setUser(user);
        petMapper.update(pet);
    }

}
